//
//  UITextView+EmotionExtension.swift
//  1215-自定义键盘
//
//  Created by 王先强 on 15/12/16.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit

extension UITextView {
    
    /// 计算出图片与文字的混合，转换为纯文本的结果
    var textStr: String {
        var attachmentStr = String()
        
        attributedText.enumerateAttribute(NSAttachmentAttributeName, inRange: NSRange(location: 0, length: attributedText.length), options: []) { (attachment, range, _) -> Void in
            if let att = attachment as? WQEmotionAttachment {
                attachmentStr += att.emotion.chs ?? ""
            }else{
                attachmentStr += (self.attributedText.string as NSString).substringWithRange(range)
            }
        }
       return attachmentStr
    }
    
    
    
    func insertSelectedEmotion(emotion: WQEmotion) {
        
        if emotion.isEmpty {
            print("isEmpty")
            return
        }
        if emotion.isDelete {
            print("isDelete")
            deleteBackward()
            return
        }
        if (emotion.emoji != nil) {
            print("emoji")
            replaceRange(selectedTextRange!, withText: emotion.emoji!)
            return
        }
        insertImageEmotion(emotion)
        delegate?.textViewDidChange!(self)
        return
    }
    
    private func insertImageEmotion(emotion: WQEmotion) {
        //富文本的图片附件
        let attachement = WQEmotionAttachment(emotion: emotion)
        attachement.image = UIImage(contentsOfFile: emotion.imagePath)
        let lineHeight = font!.lineHeight
        attachement.bounds = CGRectMake(0, -4, lineHeight, lineHeight)
        let imageText:NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachement))
        //给图片的附件设置大小，默认以前一个富文本的大小一致，如过前一个仍是图片就会改变图片大小
        imageText.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
        
        
        //取出textIntPutView的attributedText
        let oldAttriStr:NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
        let selectedRange = self.selectedRange
        oldAttriStr.insertAttributedString(imageText, atIndex: selectedRange.location)
        attributedText = oldAttriStr
        self.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
    }
}